package com.zky.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Description rabbitMq回调
 * @Author 张开源
 * @Date 2023/1/7 8:22
 * @Version 1.0
 **/
@Component
public class RabbitMqCallBack {
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 定制rabbitMq
     */
    @PostConstruct
    public void initRabbitMq() {
        //消息抵达broker就ack确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            //correlationData 唯一消息id
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //已确认消息抵达mq服务器，可能还未投递交换器
                //措施，每一个发送的消息在此做数据库数据记录，后续定期扫描未成功的数据再发送，暂时不做，后续可优化
                System.out.println("confirm....correlationData:" + correlationData);
                System.out.println("confirm....ack:" + ack);
                System.out.println("confirm....cause:" + cause);
            }
        });

        //消息抵达队列的确认回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            //只要消息没有投递到队列就失败回调
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routeKey) {
                //报错了，可能没有交换器routing-key,也可能队列不可用，总之就是投递到队列失败
                System.out.println("fail message:" + message);
                System.out.println("fail replyCode:" + replyCode);
                System.out.println("fail replyText:" + replyText);
                System.out.println("fail exchange:" + exchange);
                System.out.println("fail routeKey:" + routeKey);
                //其他补偿操作

            }
        });
    }
}
